﻿using BBCore.Core.Models.Admins;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using BBCore.Application.ViewModels.Admins;
using BBCore.Application.Admins;

namespace BBCore.Server.Controllers
{
    [ApiController]
    [Route("/api/[controller]/[action]")]
    public class AccountController : ControllerBase
    {
        private readonly IAdminService _userService;
        public AccountController(IAdminService userService) => _userService = userService;
        [HttpPost]
        public async Task<object> Login([FromBody] LoginVo loginVo)
        {
            var user = await _userService.user_LoginAsync(loginVo);
            if (user == null)
            {
                return new { Code = 50000, Message = "用户名或密码错误" };
            }

            var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
            identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName!));
            identity.AddClaim(new Claim(ClaimTypes.Role, user.RoleId.ToString()));//角色id
            //identity.AddClaim(new Claim(ClaimTypes.Role, user.UserName!));//角色名称

            await HttpContext.SignInAsync(new ClaimsPrincipal(identity), new AuthenticationProperties()
            {
                IsPersistent = true,
                ExpiresUtc = loginVo.RememberMe ? DateTimeOffset.Now.AddDays(5) : DateTimeOffset.Now.AddMinutes(60)
            });
            return new { Code = 20000, Message = "登录成功" };
        }
        [HttpGet]
        [Authorize]
        public async Task<IActionResult> Logout()
        {
            await HttpContext.SignOutAsync();
            return Redirect("/Login");
        }
    }
}
